/*
 * MainFrame.java
 *
 * Created on __DATE__, __TIME__
 */

package ui;

import java.awt.Dimension;
import java.awt.Event;
import java.awt.Point;

import javax.swing.JOptionPane;
import javax.xml.parsers.ParserConfigurationException;

import com.live.spaces.shanboli.JxtaHelper;
import com.live.spaces.shanboli.ReadXML;
import com.live.spaces.shanboli.WriteXML;

//import org.w3c.dom.*;

import foxtrot.Task;
import foxtrot.Worker;

/**
 * 
 * @author Tom Lee
 */
public class MainFrame extends javax.swing.JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JxtaHelper jh;

	protected boolean iniJXTAed = false;

	private String nickName = "JXChat2peer";

	private ReadXML my;

	/** Creates new form MainFrame */
	public MainFrame() {
		my = new ReadXML();
		nickName = my.toRead();
		initComponents();
	}

	private void iniJXTA() {
		jh = new JxtaHelper(peersTable, nickName, mainTextArea);
		jh.startJxta();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        peersTable = new javax.swing.JTable();
        inputTextField = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        mainTextArea = new javax.swing.JTextArea();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        friendNameLabel = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        aboutMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("JXChat2 by Shanbo Li");

        jLabel1.setFont(new java.awt.Font("Comic Sans MS", 1, 18));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("JXChat2");
        jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        peersTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nick Name", "IP"
            }
        ));
        peersTable.setEnabled(false);
        peersTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                handlerClickTable(evt);
            }
        });
        jScrollPane1.setViewportView(peersTable);

        mainTextArea.setColumns(20);
        mainTextArea.setEditable(false);
        mainTextArea.setFont(new java.awt.Font("Dialog", 0, 13));
        mainTextArea.setRows(5);
        jScrollPane2.setViewportView(mainTextArea);

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("ui/text"); // NOI18N
        jButton2.setText(bundle.getString("Send")); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                handlerSendMsg(evt);
            }
        });

        jLabel2.setText(bundle.getString("To:")); // NOI18N

        jButton1.setText(bundle.getString("Get_File")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jMenu1.setText(bundle.getString("File")); // NOI18N

        jMenuItem2.setText(bundle.getString("Start")); // NOI18N
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startMenu(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuBar1.add(jMenu1);

        jMenu2.setText(bundle.getString("Setup")); // NOI18N

        jMenuItem1.setText(bundle.getString("Nick_Name")); // NOI18N
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                handlerSetupNickName(evt);
            }
        });
        jMenu2.add(jMenuItem1);

        jMenuBar1.add(jMenu2);

        jMenu3.setText(bundle.getString("Help")); // NOI18N

        aboutMenuItem.setText(bundle.getString("About")); // NOI18N
        aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutMenuItemActionPerformed(evt);
            }
        });
        jMenu3.add(aboutMenuItem);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE)
                .add(15, 15, 15))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(jLabel2)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(friendNameLabel))
                    .add(layout.createSequentialGroup()
                        .add(inputTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton2)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton1))
                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE))
                .add(15, 15, 15))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 88, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel2)
                            .add(friendNameLabel))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(inputTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jButton1)
                        .add(jButton2)))
                .addContainerGap(25, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	//GEN-FIRST:event_aboutMenuItemActionPerformed
	private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
		MainFrame_AboutBox dlg = new MainFrame_AboutBox(this);
		Dimension dlgSize = dlg.getPreferredSize();
		Dimension frmSize = getSize();
		Point loc = getLocation();
		dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,
				(frmSize.height - dlgSize.height) / 2 + loc.y);
		dlg.setModal(true);
		dlg.pack();
		dlg.setVisible(true);
	}//GEN-LAST:event_aboutMenuItemActionPerformed

	//GEN-FIRST:event_jButton1ActionPerformed
	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
		jh.sendMsg("get " + inputTextField.getText());
		jh.receiveFile(".\\share\\" + inputTextField.getText());

	}//GEN-LAST:event_jButton1ActionPerformed

	//GEN-FIRST:event_handlerSendMsg
	private void handlerSendMsg(java.awt.event.ActionEvent evt) {
		jh.sendMsg(nickName + ": " + inputTextField.getText());
		mainTextArea.append(nickName + ": " + inputTextField.getText() + "\n");
	}//GEN-LAST:event_handlerSendMsg

	// GEN-FIRST:event_handlerClickTable
	private void handlerClickTable(java.awt.event.MouseEvent evt) {

		// 右击事件
		if (evt.getModifiers() == Event.META_MASK) {
			int row = peersTable.rowAtPoint(evt.getPoint());
			//int col = peersTable.columnAtPoint(evt.getPoint());
			// 选中鼠标右击的行
			peersTable.setRowSelectionInterval(row, row);
			// 弹出message框并显示内容

			int result = JOptionPane.showConfirmDialog(this,
					java.util.ResourceBundle.getBundle("ui/text").getString("See_what_this_gay_has!"), "Shared Files",
					JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);

			if (result == JOptionPane.YES_OPTION) {
				jh.sendMsg("ls");
			}

		}

		int row = peersTable.rowAtPoint(evt.getPoint());
		peersTable.setRowSelectionInterval(row, row);
		friendNameLabel.setText(peersTable.getValueAt(row, 0).toString());

	}// GEN-LAST:event_handlerClickTable

	// GEN-FIRST:event_startMenu
	private void startMenu(java.awt.event.ActionEvent evt) {
		try {
			Worker.post(new Task() {
				public Object run() throws Exception {
					if (iniJXTAed == false) {
						iniJXTA();
						iniJXTAed = true;
					}
					return null;
				}
			});
		} catch (Exception ignored) {
		}

	}// GEN-LAST:event_startMenu

	// GEN-FIRST:event_handlerSetupNickName
	private void handlerSetupNickName(java.awt.event.ActionEvent evt) {
		String title = java.util.ResourceBundle.getBundle("ui/text").getString("Input_your_new_nick_name");
		String message = java.util.ResourceBundle.getBundle("ui/text").getString("Your_nick_name_is_") + nickName + java.util.ResourceBundle.getBundle("ui/text").getString("_now");
		int messageType = JOptionPane.QUESTION_MESSAGE;
		String old = nickName;

		nickName = JOptionPane.showInputDialog(this, message, title,
				messageType);

		if (nickName != null) {
			WriteXML myxml;
			try {
				myxml = new WriteXML();
				myxml.toWrite(nickName);
				myxml.toSave();
			} catch (ParserConfigurationException e) {

				// e.printStackTrace();
			}

		} else {
			nickName = old;
		}

	}// GEN-LAST:event_handlerSetupNickName

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new MainFrame().setVisible(true);
			}
		});
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JLabel friendNameLabel;
    private javax.swing.JTextField inputTextField;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea mainTextArea;
    private javax.swing.JTable peersTable;
    // End of variables declaration//GEN-END:variables

}